package com.hxh.ocean.controller
{
	import com.hxh.ocean.events.Events;
	import com.hxh.ocean.model.StageModel;
	import com.hxh.utils.Common;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	import mx.controls.Alert;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.soap.LoadEvent;
	import mx.rpc.soap.WebService;

	public class DatabaseManager extends EventDispatcher
	{
		private var _stageModel:StageModel;
		private var _stageService:WebService;
		
		public function DatabaseManager()
		{
			_stageService = new WebService();
			_stageService.wsdl = "http://main.hxhieu.net/Services/StageService.asmx?WSDL";
			//_stageService.wsdl = "http://localhost:9999/OceanCS4Services/StageService.asmx?WSDL";
			_stageService.loadWSDL();
			if (_stageService.canLoadWSDL()){
				_stageService.addEventListener(LoadEvent.LOAD, stageLoaded);
			}
			else{
				Alert.show("Error! Please contact Hugh!");
			}
		}
		
		public function get StageInfo():StageModel
		{
			return _stageModel;
		}

		public function setBGColor(color:uint):void
		{
			_stageModel.BackgroundColor = color;
			_stageService.setStageColor(color);
			_stageService.setStageColor.addEventListener(ResultEvent.RESULT, changesSaved);			
		}
		
		public function setStageMusic(val:Boolean):void{
			_stageModel.PlayMusic = val;
			_stageService.setStageMusic(val);
			_stageService.setStageMusic.addEventListener(ResultEvent.RESULT, changesSaved);
		}
		
		public function setStageSound(val:Boolean):void{
			_stageModel.PlaySFX = val;
			_stageService.setStageSound(val);
			_stageService.setStageSound.addEventListener(ResultEvent.RESULT, changesSaved);
		}
		
		public function setStageLabel(val:Boolean):void{
			_stageModel.ShowLabel = val;
			_stageService.setStageLabel(val);
			_stageService.setStageLabel.addEventListener(ResultEvent.RESULT, changesSaved);	
		}
				
		private function stageLoaded(evt:Event):void
		{
			_stageService.getStageInfo();
			_stageService.getStageInfo.addEventListener(ResultEvent.RESULT, getStageInfo);
		}
		
		private function getStageInfo(evt:ResultEvent):void{
			
			var result:String = evt.result as String;
			var info:Array = result.split(",");
			_stageModel = new StageModel(uint(info[0]),
										Common.strToBool(info[1]),
										Common.strToBool(info[2]),
										Common.strToBool(info[3]));
			dispatchEvent(new Event(Events.STAGE_INFO_LOADED));
		}
		
		private function changesSaved(evt:ResultEvent):void{
			if (evt.result as Boolean){
				dispatchEvent(new Event(Events.CHANGES_SAVED));
			}
		}
	}
}